package Client;

import java.awt.event.MouseEvent;
import java.awt.event.MouseListener;
import java.awt.event.WindowEvent;
import java.awt.event.WindowListener;
import java.util.Observable;
import java.util.Observer;

import javax.swing.JFrame;

public class ClientGUI implements Observer {

	private int width;
	private int height;
	private int blocksize;

	private JFrame frame;
	private Grid grid;

	private Client client;
	private boolean snakePress = false;

	public ClientGUI(Client client) {
		this.client = client;
		client.addObserver(this);
	}

	public void getDimensionsForGUI(int width, int height, int blocksize) {
		this.width = width;
		this.height = height;
		this.blocksize = blocksize;
		createFrame();
	}

	private void createFrame() {
		frame = new JFrame("Snake Multiplayer");
		grid = new Grid(width, height, blocksize);
		frame.setSize(width, height);
		frame.add(grid);
		frame.setResizable(false);
		frame.setLocationRelativeTo(null);
		frame.setDefaultCloseOperation(JFrame.EXIT_ON_CLOSE);
		frame.setVisible(true);
		frame.addWindowListener(new WindowListener() {

			@Override
			public void windowOpened(WindowEvent arg0) {
			}

			@Override
			public void windowIconified(WindowEvent arg0) {
			}

			@Override
			public void windowDeiconified(WindowEvent arg0) {
			}

			@Override
			public void windowDeactivated(WindowEvent arg0) {
			}

			@Override
			public void windowClosing(WindowEvent arg0) {
				stop();
			}

			@Override
			public void windowClosed(WindowEvent arg0) {
			}

			@Override
			public void windowActivated(WindowEvent arg0) {
			}
		});
		frame.addMouseListener(new MouseListener() {

			@Override
			public void mouseReleased(MouseEvent arg0) {
			}

			@Override
			public void mousePressed(MouseEvent arg0) {
			}

			@Override
			public void mouseExited(MouseEvent arg0) {
			}

			@Override
			public void mouseEntered(MouseEvent arg0) {
			}

			@Override
			public void mouseClicked(MouseEvent e) {
				if (!snakePress) {
					clickSnake((e.getX() - 6) / blocksize, (e.getY() - 28)
							/ blocksize);
				} else {
					setSnakeDirections((e.getX() - 6), (e.getY() - 28));
				}
			}
		});

	}

	public void setSnakeDirections(int x, int y) {
		client.setSnakeDir(x, y);
		grid.setSelected(false);
		snakePress = false;
	}

	public void clickSnake(int x, int y) {
		client.clickSnake(x, y);
	}

	public Grid getGrid() {
		return grid;
	}

	public void stop() {
		client.stop();
	}

	@Override
	public void update(Observable observable, Object object) {
		grid.repaint();
	}

	public void setSnakePressed(boolean b) {
		snakePress = b;
	}

	public int getWidth() {
		return width;
	}

	public int getHeight() {
		return height;
	}

	public int getBlockSize() {
		return blocksize;
	}

}
